package com.learning.demos.jvmgc;

import sun.jvm.hotspot.utilities.BitMap;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

/**
 * @author adolphw
 *
 * 内存不够的时候就回收
 *
 * 程序读取大量本地图片，
 * 如果每次读，影响性能
 * 如果全部加载 则会oom
 */
public class SoftReferenceDemo {

    public static void softRef_memory_enough() {
        Object object1 = new Object();
        SoftReference<Object> softReference = new SoftReference<Object>(object1);

        System.out.println(object1);
        System.out.println(softReference);

        object1 = null;
        System.gc();

        System.out.println(object1);
        System.out.println(softReference);
    }

    public static void softRef_memory_not_enough() {
        Object object1 = new Object();
        SoftReference<Object> softReference = new SoftReference<Object>(object1);

        System.out.println(object1);
        System.out.println(softReference.get());

        object1 = null;


        try {
            byte[] bytes = new byte[3000 * 1024 * 1024];
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println(object1);
            System.out.println(softReference.get());
        }
    }

    public static void main(String[] args) {
        softRef_memory_enough();

        softRef_memory_not_enough();


        // 使用软弱引用避免OOM问题
        Map<String, SoftReference<BitMap>> imageCache = new HashMap<String, SoftReference<BitMap>>();

    }
}
